package org.btik.light.meta.base;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author lustre
 * @version 1.0
 * @since 2021/5/15 12:37
 */
public interface Command extends Light {

    /**
     * 设备目标
     * @return 执行的设备的sn
     * */
    String getTarget();
    /**
     * 操作码
     * @return  对应各自meta对应的rpc.
     * */
    int opCode();

    /**
     * 操作参数
     *@return 操作码可能附带参数，对应各自meta的rpc
     * */
    List<?> getParams();

    /**
     *默认编码方式
     * @return 命令对应的字节码
     * @throws IOException 见 {@link ByteArrayOutputStream#write(int)}
     * */
    default byte[] encode() throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        String cmdHead = "id:" + getCmdId() + '\n'
                + "op:" + opCode() + '\n';
        byte[] bytes = cmdHead.getBytes(StandardCharsets.UTF_8);
        byteBuffer.write(bytes);
        List<?> params = getParams();
        if(params != null) {
            for (Object param : params) {
                if (param instanceof String) {
                    byteBuffer.write(((String) param).getBytes());
                    byteBuffer.write(' ');
                } else if (param instanceof Double) {
                    byteBuffer.write(((Double) param).byteValue());
                    byteBuffer.write(' ');
                } else if (param instanceof ToByteArray) {
                    byteBuffer.write(((ToByteArray) param).toByteArray());
                    byteBuffer.write(' ');
                }
            }
        }
        byteBuffer.write('\n');
        byteBuffer.write('\n');
        return byteBuffer.toByteArray();
    }

}
